package me.joshua.tools4j.web.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class RefreshInterceptor extends HandlerInterceptorAdapter {

	@SuppressWarnings("unchecked")
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (modelAndView == null || !modelAndView.hasView()) {
			return;
		}

		String originalViewName = modelAndView.getViewName();
		if (!StringUtils.startsWith(originalViewName, "refresh:")) {
			return;
		}
		
		String url = StringUtils.join(request.getRequestURL(), request.getQueryString());
		// 调用clear阻止后续HandlerInterceptor的执行
		modelAndView.clear();
		response.sendRedirect(url);
	}
}